package pt.compflow.activity.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pt.compflow.Context;
import pt.compflow.flowontology.model.FlowOntologyModel;
import pt.compflow.flowontology.model.Task;
import pt.compflow.flowontology.model.Workflow;
import pt.compflow.interfaces.IOInterface;
import pt.compflow.interfaces.task.TaskInterface;
import pt.compflow.storage.TripleStoreConnection;
import pt.compflow.tools.OntModelHelper;

/**
 * TaskController Command to cancel a previously requested Assignment through a specific TaskInterface
 * Useful when the solution for an Assignment has meanwhile arrived through another interface
 * 
 */
public class TaskControllerCancelAssignmentCommand implements Runnable {
	
	private static final Logger LOG = LoggerFactory.getLogger(TaskControllerCancelAssignmentCommand.class);

	protected TaskControllerImpl taskController;
	protected IOInterface taskInterface;
	protected String jobUri;
	protected String taskUri;
	protected String assignmentUri;
	protected Context context;
	
	public TaskControllerCancelAssignmentCommand(Context context, TaskControllerImpl taskController, IOInterface taskInterface, String jobUri, String taskUri, String assignmentUri) {
		this.taskController = taskController;
		this.taskInterface = taskInterface;
		this.assignmentUri = assignmentUri;
		this.taskUri = taskUri;
		this.jobUri = jobUri;
		this.context = context;
	}
	
	@Override
	public void run() {
		LOG.debug("Cancelling Assignment " + assignmentUri + " of Task " + taskUri + " through Interface " + taskInterface.getInterfaceUri());
		
		TripleStoreConnection store = context.getStoreConnection();
		store.openStore();
		
		FlowOntologyModel engineModel = store.connectModel();
		FlowOntologyModel jobModel = store.connectNamedModel(jobUri);
		
		Task t = jobModel.getTaskWithURI(taskUri);
		Workflow wf = t.getActivityOfWorkflow();
		
		// get the ontology model (workflow-definition) of this workflow
		OntModelHelper ontModelHelper = context.getOntModelHelperManager().get(store, jobUri, wf.getRootWorkflow().getLocalName());
		
		// request the task t through the taskInterface
		// this is a sync call: after cancel runs, the task is considered to be cancelled in the interface
		((TaskInterface) taskInterface).cancel(context, store, ontModelHelper, jobModel, engineModel, jobUri, jobModel.getAssignmentWithURI(assignmentUri));
						
		store.closeStore();		
	}	
}
